package com.ldodds.ot.serializer;

import com.hp.hpl.jena.datatypes.RDFDatatype;
import com.hp.hpl.jena.datatypes.xsd.XSDDateTime;
import com.hp.hpl.jena.datatypes.xsd.impl.XMLLiteralType;
import com.hp.hpl.jena.rdf.model.AnonId;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.RDFVisitor;
import com.hp.hpl.jena.rdf.model.Resource;

public class StatementVisitor implements RDFVisitor
{
	private ItemSerializer itemSerializer;
	
	public StatementVisitor() {
		super();
	}

	public StatementVisitor(ItemSerializer itemSerializer) {
		this.itemSerializer = itemSerializer;
	}
	
	public Object visitBlank(Resource resource, AnonId id) {
		if (itemSerializer != null) {
			return itemSerializer.serializeBlankNode(
					resource.getModel(), resource);
		}
		return null;
	}

	public Object visitURI(Resource resource, String uri) {
		if (itemSerializer != null) {
			return itemSerializer.serialize(
					resource.getModel(), resource);
		}		
		return uri;
	}

	public Object visitLiteral(Literal literal) {
		RDFDatatype dataType = literal.getDatatype();
		if ( dataType != null) {
			if (XMLLiteralType.theXMLLiteralType.equals( dataType ) ) {
				//TODO: wrap in object?
				return literal.getString();
			}
			//should convert to appropriate Java type
			Object value =  literal.getValue();
			if ( value instanceof XSDDateTime ) {
				//FIXME likely to have incorrect time component
				return ( (XSDDateTime)value ).asCalendar().getTime();
			} else {
				return value;
			}
			
		}
		return literal.getString();
	}

}
